<script setup lang="ts">
import { shallowRef, watch, onMounted, inject, nextTick, ref } from "vue";

import { useAnki } from "./useAnki";
import { Card, startConfette } from "../share";


const p = defineProps<{
    /** 复习卡片的数据 */
    cards: Card[]
    /** 复习卡片的名字 */
    name: string
}>()

const fontClass = inject('font')

const {
    progress,
    card,
    answer,
    restart,
} = useAnki(p.cards, p.name)


const isCorrect = shallowRef(true)
const userKeys = shallowRef('')

// 聚焦输入框
onMounted(() => {
    const element = document.getElementById('input_el')
    element?.focus()
})

watch(userKeys, (newKeys) => {
    const isThreeCode = p.name === 'easy_code' && card.value!.key.length === 3;
    const keyLength = isThreeCode ? 4 : card.value!.key.length
    const correctKey = card.value!.key + (isThreeCode ? ' ' : '')
    // 多个编码没有打完就不提示错误
    if (newKeys.length < keyLength)
        return
    // 检查回答
    if (newKeys === correctKey) {
        answer(isCorrect.value)
        isCorrect.value = true
    } else {
        isCorrect.value = false
    }
    // 清空输入
    userKeys.value = ''
})


// 烟花效果
const showConfetti = shallowRef(false)
watch(progress, async (newV, oldV) => {
    const newLearn = newV.meet
    const oldLearn = oldV.meet
    if (newLearn === p.cards.length && newLearn > oldLearn) {
        showConfetti.value = true
        await nextTick()
        startConfette()
    }
})

const hit = []
const hitSpeed = ref(0)
const maxCount = 20
let start;
let id;
const cusRestart = () => {
    if (!confirm(`重置进度需要清空数据，无法撤回，您确定继续吗？`)) return;

    stopTimer()
    elapsed.value = '00:00:00'
    restart()
}
const shouldStart = () => !id
const stopTimer = () => {
  clearInterval(id)
  id = undefined;
}
const startTimer = () => {
  start = Date.now() 
  elapsed.value = '00:00:00'
  id = setInterval(() => {
    elapsed.value = toClock(Date.now() - start)
  }, 1000);
}
const keypress = (e) => {
  if (shouldStart()) {
    startTimer()
  }
  hit.push(e.timeStamp)
  if (hit.length > maxCount) hit.shift()
  if (hit.length < 3) return;
  const duration  = hit[hit.length - 1] - hit[0];
  hitSpeed.value = Math.floor(hit.length / duration * 1000 * 100) / 100
}
function toClock(ms) {
  let seconds = Math.floor(ms / 1000)
  const time = []
  while (seconds > 0) {
    time.push(seconds % 60)
    seconds = Math.floor(seconds / 60)
  }
  if (time.length > 3) return '[time excceeded]'
  while (time.length < 3) time.push(0)
  return time.reverse().map(n => n.toString().padStart(2, '0')).join(':') 
}

let elapsed = ref('00:00:00')
function addSpaceIfThree(key) {
  if (p.name === 'easy_code' && key.length === 3) {
  return key + '_'
  }
  return key
}
</script>

<template>
    <div
        :class="['md:w-2/3 w-full shadow-sm my-12 pb-24 bg-opacity-10 transition-color rounded-md', { 'bg-red-700': !isCorrect, 'bg-slate-500': isCorrect }]">
        <div class="flex justify-center mb-24">
            <progress class="progress w-full" :value="progress.familiar" :max="cards.length" />
        </div>
        <template v-if="!showConfetti">
            <div class="flex justify-around mb-8">

                <div :key="card.name"
                    :class="['text-6xl animate__animated', { 'text-red-400': !isCorrect, 'animate__headShake': !isCorrect }]">
                    {{ card.name }}</div>


            </div>
            <div class="flex justify-center p-5">
                <input id="input_el" type="text" placeholder="输入编码" @input="keypress" v-model="userKeys"
                    :class="['input w-half max-w-xs input-bordered text-center input-sm dark:bg-slate-800 bg-white', { 'input-error': !isCorrect }]" />
            </div>
            <div :class="['text-center', { 'opacity-0': isCorrect }]">答案是 <b class="font-mono">{{ addSpaceIfThree(card.key)}}</b>
                <span :class="['kaiti-font', fontClass]" v-if="'comp' in card">（{{ card.comp }}）</span>
            </div>
        </template>

        <template v-else>
            <div class="p-10 text-6xl text-center font-bold text-orange-800 font-sans tracking-widest -rotate-6">
                🎉恭喜过关!!</div>
            <div class="flex justify-center mt-10">
                <button class="btn btn-success" @click="_ => showConfetti = false">继续练习</button>
            </div>
        </template>

    </div>

    <div class="text-gray-500 flex justify-between" v:if="p.name === 'easy_code'">
        <div class="text-gray-500">Tips: 三码需要多打一个空格</div>
    </div>
    <div class="text-gray-500 flex justify-between">
        <div class="text-gray-500">训练进度： {{ progress.meet }} / {{ cards.length }}</div>
        <div class="text-gray-500">击键：{{hitSpeed}} (hit 20+ 开始，取最后20次击键)</div>
        <div class="text-gray-500">用时：{{elapsed }} (页面刷新后重置)</div>
        <button class="btn btn-ghost btn-sm font-light" @click=" cusRestart()">restart</button>
    </div>
</template>
